package com.example.studentregistration.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.example.studentregistration.pojo.Clazz;
import com.example.studentregistration.service.ClazzService;
import com.example.studentregistration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

import java.util.List;

@RestController
@RequestMapping("/api")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    @PostMapping("/clazz")
    public Result<?> insert(@RequestBody Clazz clazz) {
        return clazzService.insertClazz(clazz);
    }

    @PutMapping("/clazz")
    public Result<?> update(@RequestBody Clazz clazz) {
        return clazzService.updateClazz(clazz);
    }

    @DeleteMapping("/clazz/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        return clazzService.deleteClazz(id);
    }

    @GetMapping("/clazz")
    public Result<?> page(@RequestParam(defaultValue = "1") Integer currentPage,
                          @RequestParam(defaultValue = "10") Integer pageSize,
                          @RequestParam(required = false) Integer grade,
                          @RequestParam(required = false) String className) {
        Page<Clazz> page = clazzService.queryClazzPage(currentPage, pageSize, grade, className);
        PageInfo<Clazz> info = new PageInfo<>(page);
        return Result.success(info);
    }


    @GetMapping("/clazz/{id}")
    public Result<Clazz> get(@PathVariable Integer id) {
        return clazzService.queryClazzById(id);
    }

    @DeleteMapping("/clazz/batch")
    public Result<?> batchDelete(@RequestBody List<Integer> ids) {
        return clazzService.batchDeleteClazz(ids);
    }

    // 导出
    @GetMapping("/clazz/export")
    public void exportClazz(HttpServletResponse response) throws IOException {
        clazzService.exportClazzExcel(response);
    }

    // 导入
    @PostMapping("/clazz/import")
    public Result<?> importClazz(MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(is);
        List<Clazz> list = reader.readAll(Clazz.class);   // 直接映射
        try {
            list.forEach(clazzService::insertClazz);      // 批处理
        } catch (Exception e) {
            return Result.fail("导入失败：" + e.getMessage());
        }
        return Result.success("班级数据导入成功");
    }
     // 根据班级名字查询查询
     @GetMapping("/clazzGetByClassName/{className}")
     public Result<?> getByClassName(@PathVariable String className) {
         return clazzService.queryClazzByClassName( className);
     }
}
